<template>
  <div>
     <!-- 面包屑 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理

        </el-breadcrumb-item>
        <el-breadcrumb-item>角色列表

        </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" icon="el-icon-plus" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-row    style="padding-left: 50px;" :class="['bdbottom', index1 === 0 ? 'bdtop': '','vcenter']" 
              v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightId(scope.row,item1.id)"> 
                  {{ item1.authName }} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过v-for循环渲染二级权限 -->
                <el-row :class="[index2 === 0 ? '' :'bdtop','vcenter']" 
                  v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable 
                      @close="removeRightId(scope.row,item2.id)" >{{item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id"
                      closable @close="removeRightId(scope.row,item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column align="center" label="#" type="index"></el-table-column>
        <el-table-column align="center" label="角色名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!-- slot-scope="scope" -->
           <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRelos(scope.row.id)">编辑</el-button>
           <el-button type="danger"  size="mini" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
           <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <AddRoles ref="addRelosRef" @getRolesList="getRolesList"></AddRoles>
    <!-- 编辑角色 -->
    <EdirRoles ref="editRelosRef" @getRolesList="getRolesList" :EditRolesFrom="EditForm"></EdirRoles>
    <!-- 分配权限对话框 -->
    <SetRight ref="SetRightRef" @getRolesList="getRolesList" :roleId="roleId" :rightsList="rightsList" :defKeys="defKeys" 
      @setRightDialogClosed="setRightDialogClosed"></SetRight>
  </div>
</template>

<script>
import AddRoles from './AddRoles.vue';
import EdirRoles from './EdirRoles.vue';
import SetRight from './SetRight.vue';
export default {
  components:{ AddRoles,EdirRoles,SetRight },
  name: 'VueShopRoles',
  data() {
    return {
      // 角色列表
      roleList:[],
      // 编辑列表
      EditForm:[],
      // 权限树
      rightsList:[],
      // 传递子组件(默认选中节点id)
      defKeys:[],
      roleId:"",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 清空默认选中
    setRightDialogClosed(){
      this.defKeys = [];
    },
    /**
     * @获取角色列表
     */
    async getRolesList(){
      const {data:res} = await this.$http.get('roles');
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.roleList = res.data;
    },
    /**
     * @name addRoles()
     * @添加角色
     */
    addRoles(){
      this.$refs.addRelosRef.addDialogVisible = true;
    },
    /**
     * @name deleteRoles()
     * @删除角色
     */
    async deleteRoles(id){
      const roles = await this.$confirm('是否永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(roles == 'cancel'){
          return;
        }else{
          const {data:{meta:{status,msg}}} = await this.$http.delete(`roles/${id}`);
          if(status !== 200) {
            return this.$message.error('删除角色失败');
          }
          this.$message.success(msg);
          this.getRolesList();
        }
    },
    /**
     * @name editRoles()
     * @编辑角色 (根据id查询角色)
     */
    async editRelos(id){
      this.$refs.editRelosRef.EditDialogVisible = true;
      const {data:res} = await this.$http.get(`roles/${id}`);
      if(res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败');
      }
      this.EditForm = res.data;
    },
    /**
     * @name removeRightId()
     * @根据id删除角色权限
     */
    async removeRightId(role,rightId){
      const confimRes =  await this.$confirm("此操作将永远删除,是否继续?",'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:"warning"
      }).catch(err => err);
      if(confimRes !== 'confirm'){
        return this.$message.info('取消删除');
      }
      // 发起删除网络请求
      const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      if(res.meta.status !== 200) {
        return this.$message.error('删除权限失败');
      }
      this.$message.success('删除权限成功');
      // 防止表格重新渲染
      role.children = res.data;
    },
    /**
     * @name showSetRightDialog()
     * @分配权限 (获取权限树)
     */
    async showSetRightDialog(role){
      this.roleId = role.id
      // 获取所有权限数据
      const{data:res} = await this.$http.get(`rights/tree`);
      if(res.meta.status !== 200){
        return this.$message.error('获取权限数据失败');
      }
      // 给权限树赋值
      this.rightsList = res.data;
      // 递归获取三级节点
      this.getLeafKeys(role,this.defKeys)
      // 显示分配权限对话框 
      this.$refs.SetRightRef.SetRightDialogVisible = true;
    },
    /**
     * @通过递归获取三级角色权限id
     */
     getLeafKeys(node,arr){
      if(!node.children) {
        // 如果当前node 节点不包含children 属性，则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item,arr);
      });
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
// 动态类名
.bdtop{
  border-top: 1px solid #eee;
}
// 动态类名
.bdbottom{
  border-bottom: 1px solid #eee;
}
// 角色权限居中
.vcenter{
  display: flex;
  align-items: center;
}
</style>